<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" class="search-form">
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="监测点">
              <el-select v-model="searchForm.monitoringId" placeholder="请选择监测点" filterable clearable style="width: 100%"
                @change="handleMonitoringChange">
                <el-option v-for="item in monitoringOptions" :key="item.monitorId" :label="item.monitorName"
                  :value="item.monitorId">
                  <div class="monitor-option">
                    <span class="monitor-name">{{ item.monitorName }}</span>
                    <span class="monitor-code">{{ item.monitorCode }}</span>
                  </div>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="时间间隔">
              <el-select v-model="searchForm.timeInterval" placeholder="请选择时间间隔" style="width: 100%"
                @change="handleTimeIntervalChange">
                <el-option v-for="item in timeIntervalOptions" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="5">
            <el-form-item label="时间范围">
              <el-date-picker v-model="searchForm.timeRange" type="datetimerange" range-separator="至"
                start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss"
                :shortcuts="timeShortcuts" @change="handleTimeRangeChange" style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <div class="form-actions">
              <el-button type="primary" @click="handleSearch" :loading="loading">
                <el-icon class="el-icon--left">
                  <Search />
                </el-icon>
                查询
              </el-button>
              <el-button @click="resetSearch">
                <el-icon class="el-icon--left">
                  <Refresh />
                </el-icon>
                重置
              </el-button>
              <el-button type="success" @click="handleExport" :disabled="tableData.length === 0">
                <el-icon class="el-icon--left">
                  <Download />
                </el-icon>
                导出Excel
              </el-button>
            </div>
          </el-col>
        </el-row>
        
      </el-form>
    </el-card>

    <!-- 数据展示区域 -->
    <div class="data-container">
      <!-- 图表展示 -->
      <el-card class="chart-card">
        <div v-if="tableData.length === 0" class="empty-chart">
          <el-empty description="暂无数据" :image-size="100" />
        </div>
        <Echarts v-else :option="flowChartOption" height="400px" :key="chartKey" />
      </el-card>

      <!-- 数据表格 -->
      <el-card class="table-card">
        <div v-if="tableData.length === 0" class="empty-table">
          <el-empty description="暂无数据" :image-size="80" />
        </div>

        <el-table v-else :data="tableData" v-loading="loading" border stripe style="width: 100%" :max-height="600">
          <el-table-column prop="timeBucket" label="统计时间" align="center" fixed="left">
            <template #header>
              <div class="table-header-cell">
                <span>统计时间</span>
                <el-tooltip content="按选择的时间间隔进行统计的时间点">
                  <el-icon>
                    <InfoFilled />
                  </el-icon>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="monitorName" label="监测点名称" align="center" show-overflow-tooltip />

          <el-table-column prop="avgFlow" label="平均流量(m³/h)" align="center" sortable>
            <template #default="{ row }">
              <span :class="getFlowValueClass(row.avgFlow)">
                {{ formatFlowValue(row.avgFlow) }}
              </span>
            </template>
          </el-table-column>

          <el-table-column prop="minFlow" label="最小值(m³/h)" align="center" sortable>
            <template #default="{ row }">
              <span :class="getFlowValueClass(row.minFlow)">
                {{ formatFlowValue(row.minFlow) }}
              </span>
            </template>
          </el-table-column>

          <el-table-column prop="maxFlow" label="最大值(m³/h)" align="center" sortable>
            <template #default="{ row }">
              <span :class="getFlowValueClass(row.maxFlow)">
                {{ formatFlowValue(row.maxFlow) }}
              </span>
            </template>
          </el-table-column>

          <el-table-column prop="sampleCnt" label="样本数" align="center" sortable>
          </el-table-column>

          <el-table-column prop="status" label="状态" align="center" fixed="right">
            <template #default="{ row }">
              <el-tag :type="getStatusTagType(row.status)" size="small">
                {{ getStatusText(row.status) }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, getCurrentInstance } from 'vue'
import { ElMessage } from 'element-plus'
import Echarts from '@/components/ECharts'
import dayjs from 'dayjs'

const { proxy } = getCurrentInstance()

// API引入
import {
  getFlowMonitoringList,
  getTimeIntervalList,
  getAmountWaterReport
} from '@/api/dispatch/analyze/water_volume_analysis'

// 时间快捷选项
const timeShortcuts = [
  {
    text: '最近1小时',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000)
      return [start, end]
    }
  },
  {
    text: '最近6小时',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 6)
      return [start, end]
    }
  },
  {
    text: '最近24小时',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24)
      return [start, end]
    }
  },
  {
    text: '最近7天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
      return [start, end]
    }
  },
  {
    text: '最近30天',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
      return [start, end]
    }
  }
]

// 搜索表单
const searchForm = reactive({
  monitoringId: '',
  timeInterval: '1h',
  timeRange: [
    dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss'),
    dayjs().format('YYYY-MM-DD HH:mm:ss')
  ]
})

// 下拉选项
const monitoringOptions = ref([])
const timeIntervalOptions = ref([
  { dictValue: '5m', dictLabel: '5分钟' },
  { dictValue: '15m', dictLabel: '15分钟' },
  { dictValue: '30m', dictLabel: '30分钟' },
  { dictValue: '1h', dictLabel: '1小时' }
])

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 图表状态
const isChartFullscreen = ref(false)
const chartKey = ref(0)

// 初始化数据
onMounted(() => {
  initData()
})

// 初始化数据
const initData = async () => {
  try {
    await fetchMonitoringList()

    // 设置默认监测点
    if (monitoringOptions.value.length > 0) {
      searchForm.monitoringId = monitoringOptions.value[0].monitorId
    }

    // 查询数据
    await fetchReportData()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  }
}

// 获取监测量列表
const fetchMonitoringList = async () => {
  try {
    const res = await getFlowMonitoringList()
    monitoringOptions.value = res.data || []
  } catch (error) {
    console.error('获取监测量列表失败:', error)
    ElMessage.error('获取监测量列表失败')
  }
}

// 获取报表数据
const fetchReportData = async () => {
  try {
    loading.value = true

    if (!searchForm.monitoringId) {
      ElMessage.warning('请选择监测点')
      return
    }

    if (!searchForm.timeRange || searchForm.timeRange.length !== 2) {
      ElMessage.warning('请选择时间范围')
      return
    }

    const params = {
      monitoringId: searchForm.monitoringId,
      timeInterval: searchForm.timeInterval,
      startTime: searchForm.timeRange[0],
      endTime: searchForm.timeRange[1]
    }

    const res = await getAmountWaterReport(params)
    tableData.value = res.data || []

    if (tableData.value.length === 0) {
      ElMessage.warning('该时间段内暂无数据')
    } else {
      ElMessage.success(`查询成功，共 ${tableData.value.length} 条记录`)
    }
  } catch (error) {
    console.error('查询报表数据失败:', error)
    ElMessage.error('查询报表数据失败')
  } finally {
    loading.value = false
  }
}

// 处理监测点变化
const handleMonitoringChange = (monitorId) => {
  if (monitorId) {
    fetchReportData()
  }
}

// 处理时间间隔变化
const handleTimeIntervalChange = (interval) => {
  if (interval) {
    fetchReportData()
  }
}

// 处理时间范围变化
const handleTimeRangeChange = (range) => {
  if (range && range.length === 2) {
    fetchReportData()
  }
}

// 处理查询
const handleSearch = () => {
  fetchReportData()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    monitoringId: monitoringOptions.value.length > 0 ? monitoringOptions.value[0].monitorId : '',
    timeInterval: '1h',
    timeRange: [
      dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss'),
      dayjs().format('YYYY-MM-DD HH:mm:ss')
    ]
  })
  handleSearch()
}

// 导出Excel
const handleExport = async () => {
  try {
    if (tableData.value.length === 0) {
      ElMessage.warning('没有数据可导出')
      return
    }

    const params = {
      monitoringId: searchForm.monitoringId,
      timeInterval: searchForm.timeInterval,
      startTime: searchForm.timeRange[0],
      endTime: searchForm.timeRange[1]
    }

    const fileName = `水量分析报表_${dayjs().format('YYYYMMDDHHmmss')}.xlsx`

    // 使用proxy.download进行导出
    proxy.download('/system/dispatchAmountWater/export', params, fileName)
    ElMessage.success('导出任务已开始')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 刷新数据
const refreshData = () => {
  fetchReportData()
}

// 切换图表全屏
const toggleChartFullscreen = () => {
  isChartFullscreen.value = !isChartFullscreen.value
  chartKey.value++
}

// 计算属性
const currentMonitorInfo = computed(() => {
  return monitoringOptions.value.find(
    item => item.monitorId === searchForm.monitoringId
  ) || {}
})

const formatTimeRange = computed(() => {
  if (!searchForm.timeRange || searchForm.timeRange.length !== 2) {
    return '-'
  }
  return `${searchForm.timeRange[0]} 至 ${searchForm.timeRange[1]}`
})

// 图表配置
const flowChartOption = computed(() => {
  const data = tableData.value
  if (data.length === 0) {
    return getEmptyChartOption()
  }

  return {
    title: {
      text: '瞬时流量趋势分析',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255,255,255,0.95)',
      borderWidth: 1,
      borderColor: '#ccc',
      textStyle: {
        color: '#333'
      },
      formatter: function (params) {
        const point = params[0]
        const data = point.data
        return `
          <div style="font-weight: bold; margin-bottom: 8px; color: #409eff">${point.axisValue}</div>
          <div style="margin: 4px 0;">平均流量: <span style="font-weight: bold; color: #67c23a">${formatFlowValue(data.value)} m³/h</span></div>
          <div style="margin: 4px 0;">最小值: <span style="color: #e6a23c">${formatFlowValue(data.minFlow)} m³/h</span></div>
          <div style="margin: 4px 0;">最大值: <span style="color: #f56c6c">${formatFlowValue(data.maxFlow)} m³/h</span></div>
          <div style="margin: 4px 0;">样本数: <span style="color: #909399">${data.sampleCnt}</span></div>
          <div style="margin: 4px 0;">状态: <span style="color: ${getStatusColor(data.status)}">${getStatusText(data.status)}</span></div>
        `
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: 80,
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.map(item => formatChartTime(item.timeBucket)),
      axisLabel: {
        rotate: 45,
        formatter: function (value) {
          return dayjs(value).format('MM-DD HH:mm')
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '流量 (m³/h)',
      nameLocation: 'end',
      nameGap: 15,
      nameTextStyle: {
        fontSize: 12
      },
      axisLine: {
        show: true
      }
    },
    series: [{
      name: '平均流量',
      type: 'line',
      data: data.map(item => ({
        value: item.avgFlow,
        minFlow: item.minFlow,
        maxFlow: item.maxFlow,
        sampleCnt: item.sampleCnt,
        status: item.status
      })),
      smooth: true,
      symbol: 'circle',
      symbolSize: 6,
      itemStyle: {
        color: '#409eff'
      },
      lineStyle: {
        width: 3
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0,
            color: 'rgba(64, 158, 255, 0.3)'
          }, {
            offset: 1,
            color: 'rgba(64, 158, 255, 0.1)'
          }]
        }
      }
    }]
  }
})

// 工具函数
const formatFlowValue = (value) => {
  if (value == null || value === '') return '-'
  return typeof value === 'number' ? value.toFixed(2) : value
}

const getFlowValueClass = (value) => {
  if (value == null) return ''

  const numValue = Number(value)
  if (isNaN(numValue)) return ''

  const currentMonitor = currentMonitorInfo.value
  if (currentMonitor.alarmMin && currentMonitor.alarmMax) {
    if (numValue < currentMonitor.alarmMin) return 'flow-low'
    if (numValue > currentMonitor.alarmMax) return 'flow-high'
  }

  return 'flow-normal'
}

const getStatusTagType = (status) => {
  switch (status) {
    case 'NORMAL': return 'success'
    case 'ABNORMAL': return 'danger'
    case 'MISSING': return 'warning'
    default: return 'info'
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 'NORMAL': return '正常'
    case 'ABNORMAL': return '异常'
    case 'MISSING': return '缺失'
    default: return status || '-'
  }
}

const getStatusColor = (status) => {
  switch (status) {
    case 'NORMAL': return '#67c23a'
    case 'ABNORMAL': return '#f56c6c'
    case 'MISSING': return '#e6a23c'
    default: return '#909399'
  }
}

const getTimeIntervalLabel = (value) => {
  const option = timeIntervalOptions.value.find(item => item.dictValue === value)
  return option ? option.dictLabel : value
}

const formatChartTime = (timeString) => {
  if (!timeString) return ''
  return dayjs(timeString).format('YYYY-MM-DD HH:mm:ss')
}

const getEmptyChartOption = () => {
  return {
    title: {
      text: '暂无数据',
      left: 'center',
      top: 'center',
      textStyle: {
        color: '#999',
        fontSize: 16
      }
    },
    xAxis: { show: false },
    yAxis: { show: false },
    series: []
  }
}
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
}

.form-actions {
  text-align: center;
}

.monitor-info-card {
  margin-top: 15px;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.info-item {
  margin: 5px 0;
}

.info-label {
  color: #666;
  font-weight: bold;
}

.info-value {
  color: #409eff;
}

.monitor-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.monitor-name {
  font-weight: bold;
}

.monitor-code {
  color: #909399;
  font-size: 12px;
}

.data-container {
  display: flex;
  flex-direction: column;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.table-card {
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.data-count {
  color: #666;
  font-size: 14px;
}

.time-range {
  color: #909399;
  font-size: 12px;
}

.empty-chart,
.empty-table {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
}

.table-header-cell {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* 流量值样式 */
.flow-normal {
  color: #67c23a;
}

.flow-high {
  color: #f56c6c;
  font-weight: bold;
}

.flow-low {
  color: #e6a23c;
  font-weight: bold;
}

:deep(.el-table) {
  .cell {
    white-space: nowrap;
  }
}

:deep(.el-card) {
  margin-bottom: 20px;
}

:deep(.el-card):last-child {
  margin-bottom: 0;
}

@media (max-width: 768px) {
  .search-form .el-col {
    margin-bottom: 15px;
  }

  .table-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .table-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
}

.search-card :deep(.el-form-item) {
    margin-bottom: 0px !important;
}
</style>